package vm

import (
	"encoding/binary"
	"fmt"
	"os"
)

var running = true

// 加载镜像
func load(rom string) bool {
	// 打开二进制文件
	file, err := os.Open(rom)
	if err != nil {
		fmt.Println("无法打开文件:", err)
		return false
	}
	defer file.Close()

	// 获取文件的大小
	fileInfo, _ := file.Stat()
	fileSize := fileInfo.Size()

	// 读取文件中的数据
	buffer := make([]byte, 2)

	_, err = file.Read(buffer)
	if err != nil {
		return false
	}
	orign := binary.LittleEndian.Uint16(buffer)
	orign = swap16(orign)
	var n uint16 = 0
	for {
		_, err := file.Read(buffer)
		if err != nil {
			break
		}
		value := binary.LittleEndian.Uint16(buffer)
		MemoryWrite(orign+n, swap16(value))
		n++
	}
	fmt.Printf("load rom: %s size:%d\n", rom, fileSize)
	return true
}

var debug = false
var showLogBegin = 13
var showLogEnd = 30

// 运行镜像
func Run(rom string) {
	if !load(rom) {
		fmt.Printf("failed to load rom: %s\n", rom)
		return
	}
	n := 0
	for running {
		instr := MemoryRead(reg[R_PC])
		reg[R_PC]++
		ins(instr)

		if debug && n >= showLogBegin && n <= showLogEnd {
			fmt.Printf("指令序号:%d 执行指令:%x op:%x opbit:%x\t========>", n, instr, instr>>12, uint16(1<<(instr>>12)))
			for i := 0; i < R_COUNT; i++ {
				fmt.Printf("reg[%d]:%x\t", i, reg[i])
			}
			fmt.Println()
		}
		n++
	}
}
